package com.leyou.item.service.impl;

import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.ISpecGroupService;
import com.leyou.item.service.ISpecParamService;
import com.leyou.test.enums.ExceptionEnum;
import com.leyou.test.exceptions.LyException;
import com.leyou.utils.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl implements ISpecGroupService{

    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private ISpecParamService specParamService;

    /**
     * 根据分类查询规格组
     * @param id
     * @return
     */
    @Override
    public List<SpecGroupDTO> queryGroupByCategory(Long id) {
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(id);
        List<SpecGroup> list = specGroupMapper.select(specGroup);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SpecGroupDTO.class);
    }

    /**
     * 根据分类查询规格组,及组内参数
     * @param id
     * @return
     */
    @Override
    public List<SpecGroupDTO> querySpecsByCid(Long id) {
        //查询规格组
        List<SpecGroupDTO> specGroupDTOS = queryGroupByCategory(id);
        //查询所有规格参数
        List<SpecParamDTO> specParamDTOS = specParamService.querySpecParams(null, id, null);
        //把规格参数根据规格组groupId进行分类
        Map<Long, List<SpecParamDTO>> paramsMap = specParamDTOS.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //将参数放进specDTO中
        specGroupDTOS.forEach(specGroupDTO -> {
            specGroupDTO.setParams(paramsMap.get(specGroupDTO.getId()));
        });
        return specGroupDTOS;
    }
}
